package com.huayi.gg.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

public class Utils {
    private static final String TAG = Utils.class.getName();

    /**
     * 获取设备ID
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getDeviceID(Context context) {
        String id;
        //android.telephony.TelephonyManager
        TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (mTelephony.getDeviceId() != null) {
            id = mTelephony.getDeviceId();
        } else {
            //android.provider.Settings;
            id = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return id;
    }

    /**
     * 检查文件路径是否可用
     *
     * @param path
     * @return
     */
    public static boolean checkFilePath(String path) {
        if (path.isEmpty()) {
            return false;
        }
        //判断文件是否存在
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * 获取文件名字
     *
     * @param path
     * @return
     */
    public static String getFileName(String path) {
        if (path.isEmpty()) {
            return "";
        }
        //判断文件是否存在
        File file = new File(path);
        if (file.exists()) {
            return file.getName();
        }
        return "";
    }

    /**
     * byte数组截取
     *
     * @param data
     * @param startIndex
     * @param length
     * @return
     */
    public static byte[] subArray(byte[] data, int startIndex, int length) {

        if (data == null || data.length < length) {
            //无法截取
            return null;
        }

        byte[] result = new byte[length];

        for (int i = 0; i < result.length; i++) {
            result[i] = data[startIndex + i];
        }
        return result;
    }

    public static String byteArray2String(byte[] data) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            sb.append(int2HexStr(data[i]));
        }
        return sb.toString();
    }

    public static String int2HexStr(int i) {
        int h = (i & 0xF0) >> 4;
        int l = i & 0x0F;
        return signleInt2HexString(h) + signleInt2HexString(l);
    }

    private static String signleInt2HexString(int i) {
        if (i >= 0 && i <= 9) {
            return i + "";
        } else if (i == 10) {
            return "A";
        } else if (i == 11) {
            return "B";
        } else if (i == 12) {
            return "C";
        } else if (i == 13) {
            return "D";
        } else if (i == 14) {
            return "E";
        } else if (i == 15) {
            return "F";
        }
        return null;
    }

    /**
     * byte转16进制字符串
     *
     * @param b
     * @return
     */
    public static String byte2HexStr(byte b) {
        int t = 0xFF & b;
        return int2HexStr(t);
    }

    /**
     * 检查id是否在数组内
     *
     * @param id
     * @param ids
     * @return
     */
    public static boolean checkStringInArray(String id, String[] ids) {

        if (id.isEmpty() && ids != null && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                if (id.equals(ids[i])) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取md5摘要
     *
     * @param toencode
     * @return
     */
    public static String md5Encode(byte[] toencode) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(toencode);

            return byteArray2String(md5.digest()).toLowerCase();
//            return HexEncode(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将文件所有字节读到数组
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] getFileContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            //文件太大了
//            System.out.println("file too big...");
            return null;
        }
        return getFileContent(file);
    }

    public static byte[] getFileContent(File file) throws IOException {

        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        fi.close();
        return buffer;
    }

    /**
     * 字符串数组转为一个字符串
     *
     * @param strArray
     * @return
     */
    public static String strArray2Str(String[] strArray) {
        StringBuilder sb = new StringBuilder();
        if (strArray != null) {
            for (int i = 0; i < strArray.length; i++) {
                sb.append(strArray[i]);
            }
        }
        return sb.toString();
    }

    /**
     * 判断某个Activity 界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     * @return
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);
        if (serviceList == null || serviceList.size() <= 0) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 获取正在运行的Service数量
     *
     * @param mContext
     * @param className
     * @return
     */
    public static int getServiceRunningSum(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);
        if (serviceList == null || serviceList.size() <= 0) {
            return 0;
        }

        int sum = 0;
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                sum++;
            }
        }
        return sum;
    }

    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hideInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = activity.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
    /**
     * 立马重启应用
     *
     * @param context
     */
    public static void startAppNow(Context context) {
        startAppDelayed(context, 0);
    }

    /**
     * 重新启动当前应用
     *
     * @param context
     * @param delayMillis 延时多少毫秒
     */
    public static void startAppDelayed(Context context, long delayMillis) {
        startAppDelayed(context, delayMillis, null);
    }

    /**
     * 重新启动当前应用
     *
     * @param context
     * @param delayMillis 延时多少毫秒
     * @param extra       重启应用附带的参数
     */
    public static void startAppDelayed(Context context, long delayMillis, Bundle extra) {
        startAppDelayed(context, delayMillis, extra, context.getPackageName());
    }

    /**
     * 重新启动当前应用
     *
     * @param context
     * @param delayMillis 延时多少毫秒
     * @param extra       重启应用附带的参数
     * @param packageName 重启的应用的包名
     */
    public static void startAppDelayed(Context context, long delayMillis, Bundle extra, String packageName) {

        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            if (extra != null) {
                intent.putExtras(extra);
            }

            PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
                mgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMillis, restartIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
                mgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMillis, restartIntent);
            } else {
                mgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMillis, restartIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e(TAG, "startAppDelayed() Error={}", e.getMessage());
        }
    }

    /**
     * 判断相机是否可用
     *
     * @return true, 相机驱动可用，false,相机驱动不可用
     */
    public static boolean isCameraCanUse(int cameraId) {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open(cameraId);
        } catch (Exception e) {
            canUse = false;
            LogUtils.e(TAG, "isCameraCanUse() Error={}", e.getMessage());
        }
        if (canUse) {
            mCamera.release();
            mCamera = null;
        }
        return canUse;
    }

    /**
     * 检查摄像头是否可用
     *
     * @param cameraId
     * @return
     */
    public static boolean checkCameraEnable(int cameraId) {
        boolean result;
        Camera camera = null;
        try {
            camera = Camera.open(cameraId);
            List<Camera.Size> supportedPreviewSizes = camera.getParameters().getSupportedPreviewSizes();
            result = supportedPreviewSizes != null;
            camera.startPreview();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
            LogUtils.e(TAG, "checkCameraEnable()1 Error={}", e.getMessage());
        } finally {
            if (camera != null) {
                try {
                    camera.stopPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(TAG, "checkCameraEnable()2 Error={}", e.getMessage());
                }
                try {
                    camera.setPreviewCallback(null);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(TAG, "checkCameraEnable()3 Error={}", e.getMessage());
                }

                try {
                    camera.setPreviewCallbackWithBuffer(null);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(TAG, "checkCameraEnable()4 Error={}", e.getMessage());
                }

                try {
                    camera.release();
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(TAG, "checkCameraEnable()5 Error={}", e.getMessage());
                }
                camera = null;
            }
        }
        return result;
    }

    /**
     * 获取本地IP地址
     *
     * @return
     */
    public static List<String> getLocalIpAddress() {

        List<String> ipList = new ArrayList<>();
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddress = inetAddress.getHostAddress().toString();
                        if (!ipAddress.contains("::")) {
                            ipList.add(ipAddress);
                        } else {
                            continue;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            LogUtils.e(TAG, "getLocalIpAddress Error={}", ex.getMessage());
        }
        return ipList;
    }

    /**
     * 重启设备
     */
    public static void reboot() {
        String cmd = "su -c reboot";
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception e) {
            LogUtils.e(TAG, "重启失败! Error={}", e.getMessage());
        }
    }

    /**
     * 查看数字是否在数组
     *
     * @param i
     * @param array
     * @return
     */
    public static boolean isIntInArray(int i, int[] array) {
        if (array != null) {
            for (int temp : array) {
                if (temp == i) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * assets里的文件保存到本地
     *
     * @param context
     * @param fileName assets下的文件名
     * @param path     存储路径
     */
    public static void copyApkFromAssets(Context context, String fileName, String path) {
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e(TAG,"copyApkFromAssets() ERROR={}", e.getMessage());
        }
    }

    /**
     * 获取Bitmap的亮度
     *
     * @param bm
     * @return
     */
    public static int getBright(Bitmap bm) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        int r, g, b;
        int count = 0;
        int bright = 0;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                count++;
                int localTemp = bm.getPixel(i, j);
                r = (localTemp | 0xff00ffff) >> 16 & 0x00ff;
                g = (localTemp | 0xffff00ff) >> 8 & 0x0000ff;
                b = (localTemp | 0xffffff00) & 0x0000ff;
                bright = (int) (bright + 0.299 * r + 0.587 * g + 0.114 * b);
            }
        }
        return bright / count;
    }

    /**
     * 调节Activity的亮度
     *
     * @param context
     * @param brightness
     */
    public static void setLight(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
        LogUtils.i(TAG,"亮度:{}", brightness);
    }

    /**
     * 关闭屏幕 ，其实是使系统休眠
     */
    public static void goToSleep(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        try {
            powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    /**
     * 唤醒屏幕,停止系统休眠
     *
     * @param context
     */
    public static void wakeUp(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        try {
            powerManager.getClass().getMethod("wakeUp", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    /**
     * 系统运行
     *
     * @param cmd
     * @return
     */
    public static void systemRun(String cmd) {

        boolean result = false;
        Process process = null;
        OutputStream out = null;
        try {
            process = Runtime.getRuntime().exec("su");
            out = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);
            dataOutputStream.writeBytes(cmd);
            // 提交命令
            dataOutputStream.flush();
            // 关闭流操作
            dataOutputStream.close();
            out.close();
            int value = process.waitFor();
            LogUtils.i(TAG, "运行结果：{}", value);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取ip地址，有可能获取wifi的，确定现场设备连的都是以太网网线
     *
     * @return
     */
    public static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            if (e != null) {
                LogUtils.e(TAG, "getHostIP Error={}", e.getMessage());
            } else {
                LogUtils.e(TAG,"出现异常，但是异常为空");
            }
        }
        return hostIp;
    }
	
    /**
     * 但是当我们没在AndroidManifest.xml中设置其debug属性时:
     * 使用Eclipse运行这种方式打包时其debug属性为true,使用Eclipse导出这种方式打包时其debug属性为法false.
     * 在使用ant打包时，其值就取决于ant的打包参数是release还是debug.
     * 因此在AndroidMainifest.xml中最好不设置android:debuggable属性置，而是由打包方式来决定其值.
     *
     * @param context
     * @return
     * @author SHANHY
     * @date   2015-8-7
     */
    public static boolean isApkDebugable(Context context) {
        try {
            ApplicationInfo info= context.getApplicationInfo();
            if (info != null) {
                return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
            }
        } catch (Exception e) {

        }
        return false;
    }

    public static String getVersion(Context context){
        String versionName = "";

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),0);
            versionName = packageInfo.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return versionName;
    }

    public static String getMemoryInfo(Context context) {
        String memoryInfo = "";
        //获取总内存的大小
        try {
            FileInputStream fis = new FileInputStream(new File("/proc/meminfo"));
            //包装一个一行行读取的流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
            String readLine = "";
            while ((readLine = bufferedReader.readLine()) != null) {
                if (readLine.trim().length() < 1) {
                    continue;
                } else {
                    LogUtils.i(TAG, "getMemoryInfo()=readLine="+readLine);
                    //if (readLine.indexOf("MemTotal:") > 0 || readLine.indexOf("MemFree:") > 0 || readLine.indexOf("Buffers:") > 0 || readLine.indexOf("Cached:") > 0) {
                        memoryInfo = memoryInfo + readLine;
                    //}
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        //首先获取到进程管理器
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获取到运行的进程
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        //初始化进程的集合
        //迭代所有正在运行的进程
        for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
            //获取到进程的名字
            String processName = runningAppProcess.processName;
            if (processName == context.getPackageName()){
                memoryInfo = memoryInfo + processName;

                //获取到进程的内存的基本信息
                Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(new int[]{runningAppProcess.pid});
                int totalPrivateDirty = processMemoryInfo[0].getTotalPrivateDirty() * 1024;
                memoryInfo = memoryInfo + totalPrivateDirty;
            }
        }

        LogUtils.i(TAG, "getMemoryInfo()=" + memoryInfo);
        return memoryInfo;
    }

    public static String getTopMsg(Context context) {
        String topMsg = "";

        String str1 = "/proc/cpuinfo";
        //获取总内存的大小
        try {
            FileInputStream fis = new FileInputStream(new File("/proc/cpuinfo"));
            //包装一个一行行读取的流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
            //取到所有的内存信息
            String buf = bufferedReader.readLine();
            topMsg = topMsg + buf;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        /*


        return topMsg;
        */
        /*
        LogUtils.i(TAG, "mhchen getTopMsg()context.getPackageName()=" + context.getPackageName());
        StringBuilder tv = new StringBuilder();
        try {
            String Result;
            Process p = Runtime.getRuntime().exec("top -n 1");// | grep " + context.getPackageName());

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((Result = br.readLine()) != null) {
                if (Result.trim().length() < 1) {
                    continue;
                } else {

                    String[] CPUusr = Result.split("%");
                    tv.append("USER:" + CPUusr[0] + "\n");
                    String[] CPUusage = CPUusr[0].split("User");
                    String[] SYSusage = CPUusr[1].split("System");
                    tv.append("CPU:" + CPUusage[1].trim() + " length:" + CPUusage[1].trim().length() + "\n");
                    tv.append("SYS:" + SYSusage[1].trim() + " length:" + SYSusage[1].trim().length() + "\n");
                    LogUtils.i(TAG, "getTopMsg()=" + Result);
                    //rate = Integer.parseInt(CPUusage[1].trim()) + Integer.parseInt(SYSusage[1].trim());

                    topMsg = topMsg + Result;
                    //break;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtils.e(TAG, "getCPU() Error=" + e.getMessage());
        }
        */
        LogUtils.i(TAG, "topMsg=" + topMsg);
        return topMsg;
    }

    public static String md5(String txt) {
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(txt.getBytes("GBK"));    //问题主要出在这里，Java的字符串是unicode编码，不受源码文件的编码影响；而PHP的编码是和源码文件的编码一致，受源码编码影响。
            StringBuilder buf = new StringBuilder();
            for(byte b:md.digest()){
                buf.append(String.format("%02x", b&0xff));
            }
            return  buf.toString();
        }catch( Exception e ){
            e.printStackTrace();
            return null;
        }
    }
    public  static  int timestamp(){

        return   (int)new Date().getTime()/1000;
    }

}